package com.chengliang.bbs.handler;

import com.chengliang.bbs.entry.JSONResult;
import com.chengliang.bbs.exception.ValidateCodeException;
import com.chengliang.bbs.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 登陆验证失败的请求
 * @author chengliang
 */
@Component
@Slf4j
public class FailureHandler implements AuthenticationFailureHandler {


    @Value("${security.login-page-url}")
    private String loginPagePath;

    @Override
    public void onAuthenticationFailure(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        log.info("登录信息验证失败："+e);
        String requestType = httpServletRequest.getHeader("X-Requested-With");
        //判断是否是ajax请求
        if(StringUtil.AJAX_REQUEST_TYPE.equals(requestType)){
            httpServletResponse.setContentType("application/json;charset=utf-8");
            PrintWriter out = httpServletResponse.getWriter();
            if(e instanceof ValidateCodeException){
                out.write(JSONResult.error("验证码输入不正确").toString());
            }else if(e instanceof DisabledException){
                out.write(JSONResult.error("该账户已被禁用，请联系管理员").toString());
            }else{
                out.write(JSONResult.error("用户名或密码错误").toString());
            }
            out.flush();
            out.close();
        }else{
            //跳转登录页面
            httpServletResponse.sendRedirect(loginPagePath);
        }
    }
}
